package com.deanlib.cabinet.ui.view;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.view.View;

import androidx.annotation.Nullable;

import com.deanlib.cabinet.R;
import com.deanlib.cabinet.app.Constants;
import com.deanlib.cabinet.base.BaseActivity;
import com.deanlib.cabinet.databinding.ActivityLaunchBinding;
import com.deanlib.cabinet.ui.Navigation;
import com.deanlib.cabinet.utils.UserManager;
import com.deanlib.plantern.utils.PopupUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mmkv.MMKV;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by Dean on 2022/6/13
 */
public class LaunchActivity extends BaseActivity<ActivityLaunchBinding> {

    AlertDialog loginWizardDialog = null;
    @Override
    public void initView() {
        binding.btnStart.setOnClickListener(view->loadData());
    }

    @Override
    public void loadData() {
        //请求权限
        RxPermissions rxPermissions = new RxPermissions(this);
        addDisposable(rxPermissions.request(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_WIFI_STATE
        }).subscribe(b->{
            if (b){
                if(!UserManager.getInstance().isLogin() && !MMKV.defaultMMKV().decodeBool(Constants.KEY_CLOSE_LOGIN_WIZARD, false)) {
                    View dialogView = View.inflate(this, R.layout.layout_dialog_login_wizard, null);
                    loginWizardDialog = new AlertDialog.Builder(this).setView(dialogView).setCancelable(false).show();
                    dialogView.findViewById(R.id.btnDontPrompt).setOnClickListener(view -> {
                        MMKV.defaultMMKV().encode(Constants.KEY_CLOSE_LOGIN_WIZARD, true);
                        Navigation.toMain(this);
                        finish();
                    });
                    dialogView.findViewById(R.id.btnGotoLogin).setOnClickListener(view -> {
                        Navigation.toLogin(this);
                    });
                }else {
                    Navigation.toMain(this);
                    finish();
                }

            }else {
                PopupUtils.sendToast(R.string.obtain_necessary_permissions);
                binding.btnStart.setVisibility(View.VISIBLE);
            }
        }));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_launch;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Navigation.CODE_LOGIN && resultCode == RESULT_OK){
            Navigation.toMain(this);
            finish();
        }
    }

    @Override
    public void finish() {
        if (loginWizardDialog!=null){
            loginWizardDialog.dismiss();
        }
        super.finish();
    }
}
